package com.czl.common.util;

import java.util.Collection;

import static cn.hutool.core.convert.Convert.toInt;

/**
 * 转换工具类
 *
 * @author zhangch
 * 创建日期：2019-11-15
 *
 */
public final class ConverterUtils {
	
	public static <T> T simpleCast(Object obj, Class<T> clz){
		return simpleCast(obj, clz, null);
	}
	
	public static <T> T simpleCast(Object obj, Class<T> clz, T defaultValue){
		
		if(obj == null || clz.isInstance(obj) == false){
			return defaultValue;
		}
		
		return clz.cast(obj);
	}
	
	public static Object[] toArray(Object obj){
		
		if(obj == null){
			return null;
		}
		
		Object[] objArr = null;
		
		if(obj instanceof Object[]){
			objArr = (Object[]) obj;
		} else if(obj instanceof Collection){
			Collection<?> list = (Collection<?>) obj;
			objArr = list.toArray();
		}
		
		return objArr;
	}
	
	public static <T extends Enum<T>> T toEnum(Object obj, Class<T> clz, T defaultValue){
		
		if(obj == null || clz.isEnum() == false){
			return defaultValue;
		}
		
		T value = null;
		
		if(obj instanceof Integer){
			int ordinal = toInt(obj, -1);
			T[] values = clz.getEnumConstants();
			if(ordinal >= 0 && ordinal < values.length){
				value = values[ordinal];
			}
		} else if(obj instanceof String){
			value = Enum.valueOf(clz, obj.toString());
		} else if(clz.isInstance(obj)){
			value = clz.cast(obj);
		}
		
		if(value == null) {
			return defaultValue;
		}
		
		return value;
	}
	
	public final static String toString(Object obj, String defaultValue) {
		return (obj != null) ? obj.toString() : defaultValue;
	}
	

	/**
	 * 将long型十进制数字转换成62进制字符串
	 * 
	 * @param decNum
	 * @param defaultValue
	 * 
	 */
	public final static String longToN62(Long decNum, String defaultValue) {
		return (decNum != null) ? NumberConverter.decToN62(decNum) : defaultValue;
	}
	
	/**
	 * 将62进制字符串数换成long型十进制数字
	 * 
	 * @param n62Str
	 * @param defaultValue
	 * 
	 */
	public final static Long n62ToLong(String n62Str, Long defaultValue) {
		
		Long decNum = null;
		
		try {
			decNum = NumberConverter.n62ToDec(n62Str);
		} catch(IllegalArgumentException illegalArgumentException) {
			decNum = null;
		}
		
		return (decNum != null) ? decNum : defaultValue;
	}
	
}
